<template>
  <div class="mychild-container">
      
      <!-- 顶部操作栏 -->
      <div class="top-actions">
        <el-input 
          v-model="searchNumber" 
          placeholder="搜索孩子姓名/学号" 
          class="search-input" 
          clearable
        />
        <el-button type="success" @click="openBindChildDialog">绑定新孩子</el-button>
      </div>
      

    <!-- 孩子列表-->
    <el-table 
      :data="filteredChildrenList" 
      border 
      v-loading="loading"
    >
      <el-table-column type="index" label="序号" width="60" />
      
      <el-table-column prop="number" label="学号" width="120" />
      
      <el-table-column prop="realName" label="姓名" width="100">
        <template #default="scope">
          <div class="name-container">
            <img 
              v-if="scope.row.avatar" 
              :src="scope.row.avatar" 
              alt="头像" 
              class="avatar-small"
            />
            <span>{{ scope.row.realName }}</span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="nickName" label="昵称" width="100" />
      
      <el-table-column prop="idCard" label="学籍号" width="180" />
      
      <el-table-column prop="schoolNum" label="学校编号" width="120" />
      
      <el-table-column prop="classId" label="班级ID" width="100" />
      
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <span :class="`status-tag ${statusClassMap[scope.row.status]}`">
            {{ statusTextMap[scope.row.status] }}
          </span>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="171">
        <template #default="scope">
            <el-button
              type="success"
              class="group-chat-btn"
              round
              @click="enterGroupChat(scope.row.classId)"
              icon="ChatRound"
              :disabled="!scope.row.classId"
            >
              家校群
            </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <div v-if="filteredChildrenList.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无孩子信息，请绑定孩子">
        <el-button type="primary" @click="openBindChildDialog">绑定孩子</el-button>
      </el-empty>
    </div>

    <!-- 加载状态 -->
    <el-loading v-if="loading" target=".mychild-container" text="加载中..." />

    <!-- 绑定孩子弹窗 -->
    <el-dialog title="绑定孩子" v-model="bindDialogVisible" width="500px">
      <el-form ref="bindFormRef" :model="bindForm" :rules="bindRules" label-width="120px">
        <el-form-item label="孩子学籍号" prop="idCard">
          <el-input v-model="bindForm.idCard" placeholder="请输入孩子学籍号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBindChild">确定绑定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getStudentListByNumber, updateStudentUserNum } from '../../../../api/user-parent-mychild/user-parent-mychild.js';
import {useLoginStore} from '../../../../stores/index.js'

const router = useRouter();

// 状态映射
const statusTextMap = {
  '1': '正常',
  '0': '已锁定'
};

const statusClassMap = {
  '1': 'status-active',
  '0': 'status-locked'
};

// 响应式数据
const childrenList = ref([]);
const searchNumber = ref('');
const loading = ref(false);
const bindDialogVisible = ref(false);

// 搜索过滤
const filteredChildrenList = computed(() => {
  if (!searchNumber.value) return childrenList.value;
  const keyword = searchNumber.value.toLowerCase();
  return childrenList.value.filter(child => 
    child.real_name?.toLowerCase().includes(keyword) || 
    child.number?.toLowerCase().includes(keyword) ||
    child.nick_name?.toLowerCase().includes(keyword)
  );
});

// 绑定表单
const bindForm = reactive({
  idCard: ''
});

const bindRules = reactive({
  idCard: [
    { required: true, message: '请输入孩子学籍号', trigger: 'blur' }
  ]
});

const bindFormRef = ref(null);

// 获取学生列表
const fetchStudentList = async () => {
  try {
      const loginStore = useLoginStore()
    loading.value = true;
    const result = await getStudentListByNumber(loginStore.user.number);
    childrenList.value = result.data || [];
  } catch (error) {
    ElMessage.error('获取孩子列表失败：' + (error.message || '网络错误'));
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
    fetchStudentList();
})

// 绑定孩子
const submitBindChild = async () => {
  try {
    await bindFormRef.value.validate();
    const { idCard } = bindForm;
    const loginStore = useLoginStore()
    
    loading.value = true;
    const result = await updateStudentUserNum(idCard, loginStore.user.number);
    
    if (result > 0) {
      ElMessage.success('绑定成功');
      bindDialogVisible.value = false;
      // 重新获取列表
      fetchStudentList();
      // 重置表单
      bindFormRef.value.resetFields();
    } else {
      ElMessage.error('绑定失败，请检查信息');
    }
  } catch (error) {
    ElMessage.error('绑定失败：' + (error.message || '表单验证失败'));
  } finally {
    loading.value = false;
  }
};

// 进入家校群
const enterGroupChat = (classId) => {
  if (!classId) {
    ElMessage.warning('该孩子暂无班级信息，无法进入家校群');
    return;
  }
  router.push(`/user/parent/groupChat/${classId}`);
};

// 打开绑定弹窗
const openBindChildDialog = () => {
  bindDialogVisible.value = true;
};
</script>

<style scoped lang="scss">
.mychild-container {
  padding: 24px;
  position: relative;
}

.top-actions {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;

  .search-input {
    width: 300px;
  }
}

.name-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.avatar-small {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  object-fit: cover;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
}

.status-tag {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  font-weight: normal;
}

.status-active {
  background-color: #f0fdf4;
  color: #166534;
  border: 1px solid #bbf7d0;
}

.status-locked {
  background-color: #fee2e2;
  color: #b91c1c;
  border: 1px solid #fecaca;
}
</style>